package com.hub.videobrowsdownload

import android.content.Context
import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.text.format.Formatter
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.net.URL
import javax.net.ssl.HttpsURLConnection


class BrowsMP4Prepare(url:String, webUrl:String): BrowsVideoPrepare(url, webUrl)  {

   override fun prepare(context: Context,title:String?, videoIsWrong: ((Int, Any?) -> Unit)?): BrowsVideoPrepare {
       this.title = title
       stateLiveData.postValue( 1)
        prepareJob = CoroutineScope(Dispatchers.IO).launch {
            Log.i("MP4_封面thumb", "==============================")
            Log.i("MP4_封面thumb", url)
            var fileLength = 0L
            val thumbFile =
                File(BrowsM3U8Helper.getThumbDir(context), "${System.currentTimeMillis()}_thumb.jpg")
            try {
                var httpsURLConnection0 = URL(url).openConnection() as HttpsURLConnection
                httpsURLConnection0.setRequestProperty(
                    "User-Agent",
                    "Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Mobile Safari/537.36"
                );
                httpsURLConnection0.setRequestProperty("Connection", "close");
                httpsURLConnection0.setReadTimeout(26000);
                try {
                    httpsURLConnection0.setRequestProperty(
                        "referer",
                        "https://" + URL(url).host + "/"
                    );
                } catch (e: Exception) {

                }
                httpsURLConnection0.setInstanceFollowRedirects(false);
                httpsURLConnection0.setRequestMethod("HEAD");
                httpsURLConnection0.connect();
//                val inputStream0 = httpsURLConnection0.inputStream
//                val file2 = File(context.cacheDir, "${System.currentTimeMillis()}.mp4")
//                if (!file2.exists()) {
//                    file2.createNewFile()
//                }
//                val fileOutputStream0 = FileOutputStream(file2);
//                val arr_b = ByteArray(0x400);
//                val v2 = inputStream0.read(arr_b);
//                if (v2 != -1) {
//                    fileOutputStream0.write(arr_b, 0, v2);
//                }
//                inputStream0.close();
//                fileOutputStream0.flush();
//                fileOutputStream0.close();
                val contentLengthLong = httpsURLConnection0.contentLengthLong
                if (contentLengthLong < 10000){

                    videoIsWrong?.invoke(-3, this@BrowsMP4Prepare)
                }else{
                    videoLength.postValue(contentLengthLong)
                    videoIsWrong?.invoke(1, this@BrowsMP4Prepare)
                    try {
                        val retriever = MediaMetadataRetriever()
                        val hashMap0 = hashMapOf<String, String>()
                        hashMap0["Referer"] = "https://" + URL(url).host + "/"
                        retriever.setDataSource(url, hashMap0)

                        val durationStr =
                            retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
                        val duration = durationStr?.toLong() ?: 0L
                        videoDuration.postValue( duration.toDouble())
                        try {
                            val width =
                                retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)!!
                                    .toInt()
                            val height =
                                retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)!!
                                    .toInt()

                            videoWidth.postValue( width)
                            videoHeight.postValue( height)
                        } catch (e: Exception) {

                        }
                        var frame = try {
                            retriever.getFrameAtTime(30000000)
                        } catch (e: Exception) {
                            e.printStackTrace()
                            null
                        }

                        if (frame == null) {
                            frame = try {
                                retriever.getFrameAtTime(10000000)
                            } catch (e: Exception) {
                                e.printStackTrace()
                                null
                            }
                        }


                        if (frame == null) {
                            frame = try {
                                retriever.getFrameAtTime(1000000)
                            } catch (e: Exception) {
                                e.printStackTrace()
                                null
                            }
                        }

                        if (frame == null) {
                            frame = try {
                                retriever.getFrameAtTime(0)
                            } catch (e: Exception) {
                                e.printStackTrace()
                                null
                            }
                        }

                        FileOutputStream(thumbFile).use { out ->
                            frame!!.compress(
                                Bitmap.CompressFormat.JPEG,
                                90,
                                out
                            )
                        }
                        if (thumbFile.length() > 0) {
                            thumbPath.postValue( thumbFile.absolutePath)
                            if (downloadWrapper.value != null) {
                                changeThumbToDownloadFileDir(context)
                            }
                        }
                    } catch (e: Exception) {
                        if (contentLengthLong < 500000){
                            videoIsWrong?.invoke(-3, null)
                        }
                        e.printStackTrace()
                    }
                }

            } catch (e: Exception) {
                videoIsWrong?.invoke(-3, null)
            }
            stateLiveData.postValue( 2)
        }
        return this
    }
}